import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QLabel, QTextEdit, QLineEdit, QPushButton, QFileDialog, QMessageBox
)
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm

class NameCardApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 设置窗口标题和大小
        self.setWindowTitle('桌牌生成器')
        self.setGeometry(100, 100, 400, 500)

        # 布局
        layout = QVBoxLayout()

        # 名字列表
        layout.addWidget(QLabel('名字列表（每行一个）:'))
        self.names_text = QTextEdit()
        layout.addWidget(self.names_text)

        # 字体名称
        layout.addWidget(QLabel('字体名称:'))
        self.font_name = QLineEdit('Helvetica')
        layout.addWidget(self.font_name)

        # 字体大小
        layout.addWidget(QLabel('字体大小:'))
        self.font_size = QLineEdit('24')
        layout.addWidget(self.font_size)

        # 字体颜色
        layout.addWidget(QLabel('字体颜色（例如 black, red, #0000FF）:'))
        self.font_color = QLineEdit('black')
        layout.addWidget(self.font_color)

        # 背景图片
        layout.addWidget(QLabel('背景图片路径:'))
        self.bg_image = QLineEdit()
        layout.addWidget(self.bg_image)
        self.bg_image_button = QPushButton('选择图片')
        self.bg_image_button.clicked.connect(self.select_image)
        layout.addWidget(self.bg_image_button)

        # 桌牌尺寸
        layout.addWidget(QLabel('桌牌宽度 (mm):'))
        self.card_width = QLineEdit('90')
        layout.addWidget(self.card_width)

        layout.addWidget(QLabel('桌牌高度 (mm):'))
        self.card_height = QLineEdit('55')
        layout.addWidget(self.card_height)

        # 生成按钮
        self.generate_button = QPushButton('生成PDF')
        self.generate_button.clicked.connect(self.generate)
        layout.addWidget(self.generate_button)

        # 设置布局
        self.setLayout(layout)

    def select_image(self):
        # 选择背景图片
        file_path, _ = QFileDialog.getOpenFileName(self, '选择图片', '', '图片文件 (*.jpg *.png *.jpeg)')
        if file_path:
            self.bg_image.setText(file_path)

    def generate(self):
        # 获取输入
        names = self.names_text.toPlainText().strip().split('\n')
        font_name = self.font_name.text()
        font_size = int(self.font_size.text())
        font_color = self.font_color.text()
        bg_image = self.bg_image.text()
        card_width = float(self.card_width.text()) * mm
        card_height = float(self.card_height.text()) * mm

        # 检查输入
        if not names:
            QMessageBox.critical(self, '错误', '请输入至少一个名字')
            return

        # 选择输出文件路径
        output_filename, _ = QFileDialog.getSaveFileName(self, '保存PDF文件', '', 'PDF文件 (*.pdf)')
        if not output_filename:
            return

        # 生成PDF
        self.generate_pdf(output_filename, names, font_name, font_size, font_color, bg_image, card_width, card_height)
        QMessageBox.information(self, '成功', f'PDF已生成: {output_filename}')

    def generate_pdf(self, output_filename, names, font_name, font_size, font_color, bg_image, card_width, card_height):
        c = canvas.Canvas(output_filename, pagesize=A4)
        width, height = A4

        # 计算边距和间距
        margin = 10 * mm
        spacing = 5 * mm

        # 计算每页可以放置多少个桌牌
        cards_per_row = int((width - 2 * margin) // (card_width + spacing))
        cards_per_col = int((height - 2 * margin) // (card_height + spacing))
        cards_per_page = cards_per_row * cards_per_col

        for i, name in enumerate(names):
            if i > 0 and i % cards_per_page == 0:
                c.showPage()  # 开始新的一页

            # 计算位置
            row = (i % cards_per_page) // cards_per_row
            col = (i % cards_per_page) % cards_per_row
            x = margin + col * (card_width + spacing)
            y = height - margin - (row + 1) * (card_height + spacing)

            # 创建桌牌
            self.create_name_card(c, name, font_name, font_size, font_color, bg_image, card_width, card_height, x, y)

        c.save()

    def create_name_card(self, c, name, font_name, font_size, font_color, bg_image, width, height, x, y):
        # 绘制背景图片
        if bg_image and os.path.exists(bg_image):
            c.drawImage(bg_image, x, y, width=width, height=height)

        # 设置字体和颜色
        c.setFont(font_name, font_size)
        c.setFillColor(font_color)

        # 计算文本位置（居中）
        text_width = c.stringWidth(name, font_name, font_size)
        text_x = x + (width - text_width) / 2
        text_y = y + (height - font_size) / 2

        # 绘制名字
        c.drawString(text_x, text_y, name)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = NameCardApp()
    window.show()
    sys.exit(app.exec_())